//
//  AFNRequestManager.m
//  QianLongZan
//
//  Created by 陈家将 on 16/9/20.
//  Copyright © 2016年 szteyou. All rights reserved.
//

#import "AFNRequestManager.h"
#import "AFNBaseModel.h"
#import "AFNHTTPRequestManager.h"

@implementation AFNRequestManager

+ (NSURLSessionDataTask *)POST:(NSString *)url parameter:(AFNBaseModel *)baseModel success:(AFNSuccessBlock)success failure:(AFNFailureBlock)failure {
    AFNHTTPRequestManager *httpManager = [AFNHTTPRequestManager shareInstance];
    
    NSString *postURL = nil;
    NSDictionary *newParamters = [NSDictionary dictionary];
    if (baseModel != nil) {
        postURL = [[url stringByAppendingString:baseModel.API] stringToUTF8]; // 解析路径
        NSString *tempAPI = baseModel.API;
        baseModel.API = nil; // 剔除携带信息
        
        if (baseModel.encryptionType.length) {
            baseModel.encryptionType = nil; // 剔除携带信息
            
            if (baseModel.enabledTParam.length) {
                baseModel.enabledTParam = nil;
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON 需在提出之后
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
                newParamters = @{@"param" :base64ParamterStr,@"t":[self encryptionParam:base64ParamterStr api:tempAPI]};
            }else {
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
                newParamters = @{@"param" :base64ParamterStr};
                
            }
        }else {

            if (baseModel.enabledTParam.length) {
                baseModel.enabledTParam = nil;
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                newParamters = @{@"param" :jsonParamterStr,@"t":[self encryptionParam:jsonParamterStr api:tempAPI]};
            }else {
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                newParamters = @{@"param" : jsonParamterStr};
            }
        }
    }else {
        postURL = url;
        newParamters = nil;
    }
    DBLog(@"----->请求路径: %@ \n\t请求参数: %@", postURL, newParamters);
    
    NSURLSessionDataTask *dataTask = [httpManager POST:postURL parameters:newParamters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        DBLog(@"\n======================================\n");
//        NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
//        DBLog(@"fields = %@",[fields description]);
//        NSURL *url = [NSURL URLWithString:postURL];
//        DBLog(@"\n======================================\n");
//        //获取cookie方法1
//        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url];
//        for (NSHTTPCookie *cookie in cookies) {
//            NSLog(@"cookie,name:= %@,value = %@",cookie.name,cookie.value);
//        }
//        DBLog(@"\n======================================\n");
//        [httpManager.requestSerializer setValue:cookies forHTTPHeaderField:@"Cookie"];
        
        NSInteger code = [[responseObject objectForKey:@"resultCode"] integerValue];
        success(responseObject,code);
        DBLog(@"----->请求路径:%@\n\t返回结果: %@", task.response.URL, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *dic = [error userInfo];
        failure(error, dic[@"NSLocalizedDescription"]);
        DBLog(@"----->请求路径: %@\n\t返回错误结果: %@", dic[@"NSErrorFailingURLKey"], dic[@"NSLocalizedDescription"]);
    }];
    
    return dataTask;
}

+ (NSURLSessionDataTask *)GET:(NSString *)url parameter:(AFNBaseModel *)baseModel success:(AFNSuccessBlock)success failure:(AFNFailureBlock)failure {
    AFNHTTPRequestManager *httpManager = [AFNHTTPRequestManager shareInstance];
    
    NSString *postURL = nil;
    NSDictionary *newParamters = [NSDictionary dictionary];
    if (baseModel != nil) {
        postURL = [[url stringByAppendingString:baseModel.API] stringToUTF8]; // 解析路径
        NSString *tempAPI = baseModel.API;
        baseModel.API = nil; // 剔除携带信息
        
        if (baseModel.encryptionType.length) {
            baseModel.encryptionType = nil; // 剔除携带信息
            
            if (baseModel.enabledTParam.length) {
                baseModel.enabledTParam = nil; // 剔除携带信息
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON 需在提出之后
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
                newParamters = @{@"param" :base64ParamterStr,@"t":[self encryptionParam:base64ParamterStr api:tempAPI]};
            }else {
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
               newParamters = @{@"param" :base64ParamterStr};
            }
        }else {
            
            if (baseModel.enabledTParam) {
                baseModel.enabledTParam = nil;
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                newParamters = @{@"param" :jsonParamterStr,@"t":[self encryptionParam:jsonParamterStr api:tempAPI]};
            }else {
            NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
            NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
            newParamters = @{@"param" : jsonParamterStr};
            }
        }

    }else {
        postURL = url;
        newParamters = nil;
    }
    DBLog(@"----->请求路径: %@ \n\t请求参数: %@", postURL, newParamters);
    
    NSURLSessionDataTask *dataTask = [httpManager GET:postURL parameters:newParamters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSInteger code = 0;
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            code = [[responseObject objectForKey:@"resultCode"] integerValue];
        }
        success(responseObject,code);
        DBLog(@"----->请求路径:%@\n\t返回结果: %@", task.response.URL, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *dic = [error userInfo];
        failure(error, dic[@"NSLocalizedDescription"]);
        DBLog(@"----->请求路径: %@\n\t返回错误结果: %@", dic[@"NSErrorFailingURLKey"], dic[@"NSLocalizedDescription"]);
    }];
    
    return dataTask;
}

+ (NSURLSessionDataTask *)POSTNew:(NSString *)url parameter:(AFNBaseModel *)baseModel success:(AFNSuccessBlock)success failure:(AFNFailureBlock)failure {
    AFNHTTPRequestManager *httpManager = [AFNHTTPRequestManager shareInstance];
    
    NSString *postURL = nil;
    NSDictionary *newParamters = [NSDictionary dictionary];
    if (baseModel != nil) {
        postURL = [[url stringByAppendingString:baseModel.API] stringToUTF8]; // 解析路径
        baseModel.API = nil; // 剔除携带信息
        newParamters = [baseModel mj_keyValues]; // 解释参数
        
    }else {
        postURL = url;
        newParamters = nil;
    }
    DBLog(@"----->请求路径: %@ \n\t请求参数: %@", postURL, newParamters);
    
    NSURLSessionDataTask *dataTask = [httpManager POST:postURL parameters:newParamters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSInteger code = [[responseObject objectForKey:@"resultCode"] integerValue];
        success(responseObject,code);
        DBLog(@"----->请求路径:%@\n\t返回结果: %@", task.response.URL, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *dic = [error userInfo];
        failure(error, dic[@"NSLocalizedDescription"]);
        DBLog(@"----->请求路径: %@\n\t返回错误结果: %@", dic[@"NSErrorFailingURLKey"], dic[@"NSLocalizedDescription"]);
    }];
    
    return dataTask;
}


+ (NSURLSessionDataTask *)GETNew:(NSString *)url parameter:(AFNBaseModel *)baseModel success:(AFNSuccessBlock)success failure:(AFNFailureBlock)failure {
    AFNHTTPRequestManager *httpManager = [AFNHTTPRequestManager shareInstance];
    
    NSString *postURL = nil;
    NSDictionary *newParamters = [NSDictionary dictionary];
    if (baseModel != nil) {
        postURL = [[url stringByAppendingString:baseModel.API] stringToUTF8]; // 解析路径
        baseModel.API = nil; // 剔除携带信息
        newParamters = [baseModel mj_keyValues]; // 解释参数
        
    }else {
        postURL = url;
        newParamters = nil;
    }
    DBLog(@"----->请求路径: %@ \n\t请求参数: %@", postURL, newParamters);
    
    
    NSURLSessionDataTask *dataTask = [httpManager GET:postURL parameters:newParamters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
        NSInteger code = 0;
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            code = [[responseObject objectForKey:@"resultCode"] integerValue];
        }
        success(responseObject,code);
        DBLog(@"----->请求路径:%@\n\t返回结果: %@", task.response.URL, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *dic = [error userInfo];
        failure(error, dic[@"NSLocalizedDescription"]);
        DBLog(@"----->请求路径: %@\n\t返回错误结果: %@", dic[@"NSErrorFailingURLKey"], dic[@"NSLocalizedDescription"]);
    }];
    
    return dataTask;
}

+ (NSString *)encryptionParam:(NSString *)param api:(NSString *)api {
    
    NSString *str = [NSString stringWithFormat:@"APP{app%@:param:%@:post}",api,param];
    NSString *newStr = [str md5Str];
    
    NSString *keyOne = @"%#7{";
    NSString *keytwo = @"}8#@";
    //    @"md5(%#7{md5(APP{/app/pay/createBill:param:paramBase64:post})}8#@)";
    NSString *addkeyStr = [NSString stringWithFormat:@"%@%@%@",keyOne,newStr,keytwo];
    NSString *md5Str = [addkeyStr md5Str];
    return md5Str;
}

+ (NSURLSessionDataTask *)POST:(NSString *)url constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))bodyBlock parameter:(AFNBaseModel *)baseModel success:(AFNSuccessBlock)success failure:(AFNFailureBlock)failure {
    AFNHTTPRequestManager *httpManager = [AFNHTTPRequestManager shareInstance];
    
    NSString *postURL = nil;
    NSDictionary *newParamters = [NSDictionary dictionary];
    if (baseModel != nil) {
        postURL = [[url stringByAppendingString:baseModel.API] stringToUTF8]; // 解析路径
        NSString *tempAPI = baseModel.API;
        baseModel.API = nil; // 剔除携带信息
        
        if (baseModel.encryptionType.length) {
            baseModel.encryptionType = nil; // 剔除携带信息
            
            if (baseModel.enabledTParam.length) {
                baseModel.enabledTParam = nil;
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON 需在提出之后
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
                newParamters = @{@"param" :base64ParamterStr,@"t":[self encryptionParam:base64ParamterStr api:tempAPI]};
            }else {
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                NSString *base64ParamterStr = [CommonFunc base64StringFromText:jsonParamterStr];// base64加密
                newParamters = @{@"param" :base64ParamterStr};
            }
        }else {
            
            if (baseModel.enabledTParam.length) {
                baseModel.enabledTParam = nil;
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                newParamters = @{@"param" :jsonParamterStr,@"t":[self encryptionParam:jsonParamterStr api:tempAPI]};
            }else {
                NSDictionary *paramters = [baseModel mj_keyValues]; // 解释参数
                NSString *jsonParamterStr = [paramters mj_JSONString];// 转JSON
                newParamters = @{@"param" : jsonParamterStr};
            }
        }
    }else {
        postURL = url;
        newParamters = nil;
    }
    DBLog(@"----->请求路径: %@ \n\t请求参数: %@", postURL, newParamters);
    
    NSURLSessionDataTask *dataTask = [httpManager POST:postURL parameters:newParamters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        bodyBlock(formData);//配置请求体
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSInteger code = [[responseObject objectForKey:@"resultCode"] integerValue];
        success(responseObject,code);
        DBLog(@"----->请求路径:%@\n\t返回结果: %@", task.response.URL, responseObject);
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSDictionary *dic = [error userInfo];
        failure(error, dic[@"NSLocalizedDescription"]);
        DBLog(@"----->请求路径: %@\n\t返回错误结果: %@", dic[@"NSErrorFailingURLKey"], dic[@"NSLocalizedDescription"]);
    }];
    
    
    return dataTask;

    
}

@end
